#!/bin/bash
set -euo pipefail

# 配置参数
SERVER_URL="http://172.20.3.75/register.php"
LOG_FILE="/var/log/ip_report.log"
EXCLUDE_NICS="lo docker0 veth virbr tun tap"
NIC_PRIORITY="enp wlp eth wlan"

# 日志函数
log() {
    local level="$1"  # 函数内使用local合法
    local message="$2"
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] [$level] $message" >> "$LOG_FILE"
}

# 检查依赖
check_deps() {
    local deps="jq curl ip hostname"  # 函数内使用local合法
    for dep in $deps; do
        if ! command -v "$dep" &> /dev/null; then
            log "ERROR" "缺少工具 '$dep'，请安装：sudo apt install $dep"
            exit 1
        fi
    done
}

# 获取网卡信息（MAC与IP绑定）
get_nic_info() {
    local target_mac=""  # 函数内使用local合法
    local target_ipv4=""
    local target_ipv6=""
    local selected_nic=""

    log "INFO" "开始遍历网卡"
    local active_nics=$(ip link show | grep -B1 "UP" | grep -oE "^[0-9]+: [a-zA-Z0-9_-]+:" | awk -F': ' '{print $2}' | sed 's/:$//')

    for nic in $active_nics; do
        if echo " $EXCLUDE_NICS " | grep -q " $nic "; then
            log "DEBUG" "跳过排除网卡：$nic"
            continue
        fi

        local mac=$(ip link show "$nic" | grep -oE "link/ether [0-9a-f:]{17}" | awk '{print $2}')
        if [[ -z "$mac" || "$mac" == "00:00:00:00:00:00" ]]; then
            log "DEBUG" "网卡 $nic 无有效MAC，跳过"
            continue
        fi

        local ipv4=$(ip -4 addr show "$nic" | grep -oE "inet [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+" | awk '{print $2}' | grep -v "127.0.0.1")
        local ipv6=$(ip -6 addr show "$nic" | grep -oE "inet6 [0-9a-f:]+/[0-9]+" | awk '{print $2}' | cut -d/ -f1 | grep -vE "::1|fe80::")

        if [[ -z "$ipv4" && -z "$ipv6" ]]; then
            log "DEBUG" "网卡 $nic 有MAC（$mac）但无有效IP，跳过"
            continue
        fi

        local is_high_priority=0
        for prefix in $NIC_PRIORITY; do
            if [[ "$nic" == "$prefix"* ]]; then
                is_high_priority=1
                break
            fi
        done

        if [[ $is_high_priority -eq 1 || -z "$selected_nic" ]]; then
            selected_nic="$nic"
            target_mac="$mac"
            target_ipv4="$ipv4"
            target_ipv6="$ipv6"
            log "DEBUG" "选中候选网卡：$nic（MAC：$mac，IPv4：${ipv4:-无}，IPv6：${ipv6:-无}）"
            if [[ $is_high_priority -eq 1 ]]; then
                break
            fi
        fi
    done

    if [[ -z "$selected_nic" || -z "$target_mac" ]]; then
        log "ERROR" "未找到有效网卡"
        exit 1
    fi

    echo "$target_mac|$target_ipv4|$target_ipv6"
}

# 生成JSON
generate_json() {
    local hostname="$1"  # 函数内使用local合法
    local os="$2"
    local mac="$3"
    local ipv4="$4"
    local ipv6="$5"

    local ip="${ipv4:-}-${ipv6:-}"
    log "DEBUG" "拼接IP：$ip"

    local json=$(jq -n \
        --arg hn "$hostname" \
        --arg os "$os" \
        --arg ip "$ip" \
        --arg mac "$mac" \
        '{
            "hostname": $hn,
            "os": $os,
            "ip": $ip,
            "mac": $mac
        }')

    log "DEBUG" "生成JSON：$json"
    echo "$json"
}

# 发送请求
send_request() {
    local json="$1"  # 函数内使用local合法
    log "INFO" "向PHP接口发送请求..."

    local response=$(curl -s -w "\n%{http_code}" \
        -X POST \
        -H "Content-Type: application/json" \
        -d "$json" \
        --max-time 15 \
        "$SERVER_URL")

    local http_code=$(echo "$response" | tail -n1)
    local resp_body=$(echo "$response" | head -n -1)

    if [[ "$http_code" -eq 200 ]]; then
        log "INFO" "PHP接收成功，响应：$resp_body"
    else
        log "ERROR" "PHP接收失败，状态码：$http_code，响应：$resp_body"
        exit 1
    fi
}

# -------------------------- 主流程（无任何local关键字） --------------------------
log "INFO" "=== 开始执行 ==="

check_deps

# 主流程变量：直接定义，不加local（关键修复！）
hostname=$(hostname)
os=$(lsb_release -d 2>/dev/null | cut -d: -f2 | sed 's/^[ \t]*//')
os=${os:-"unknown"}
log "DEBUG" "主机名：$hostname，操作系统：$os"

nic_info=$(get_nic_info)
IFS="|" read -r target_mac target_ipv4 target_ipv6 <<< "$nic_info"

json=$(generate_json "$hostname" "$os" "$target_mac" "$target_ipv4" "$target_ipv6")

send_request "$json"

log "INFO" "=== 执行完成 ==="
